package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.CollectionKit;
import com.wxxymaker.edu.model.entity.SysRecord;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2019/3/6 10:04
 * @DESCRIBE
 */
@Bean
public class SysRecordService {

    /**
     * 在当天的访问量上添加一，若则新建
     */
    public void addView() {
        SysRecord record = getToDay();
        if (record != null) {
            record.setViews(record.getViews() + 1);
            record.update();
        } else {
            record = new SysRecord();
            record.setViews(1L);
            record.setDate(new Date());
            record.save();
        }
    }

    /**
     * 统计所有访问量
     */
    public long countAll() {
        List<SysRecord> records = Anima.select(SysRecord::getViews).from(SysRecord.class).all();
        if (CollectionKit.isNotEmpty(records)) {
            return records.stream().mapToLong(SysRecord::getViews).sum();
        }
        return 0;
    }

    public long toDayView() {
        SysRecord toDay = getToDay();
        if (toDay != null) {
            return toDay.getViews();
        }
        return 0;
    }

    public SysRecord getToDay() {
        return select().where(SysRecord::getDate, LocalDate.now()).one();
    }

    public Page<SysRecord> getPage(int page, int limit) {
        return select().order("id", OrderBy.DESC).page(page, limit);
    }

    private AnimaQuery<SysRecord> select() {
        return Anima.select().from(SysRecord.class);
    }
}
